package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.util.HttpUtil;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import kong.unirest.HttpResponse;
import kong.unirest.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liang Jianlin
 * @date 2024-04-20 15:21
 */
public class StudentInfoController {
    Map<String,String> studentInfo = new HashMap<>();

    private Map<String,Node> paneMap = new HashMap<String,Node>();
    private Button temp;
    @FXML
    private ImageView avatar;
    @FXML
    private Label name;
    @FXML
    private Label id;
    @FXML
    private Label category;
    @FXML
    private Button basicInformation;
    @FXML
    private Button honorsButton;
    @FXML
    private Button academicButton;
    @FXML
    private Button activityButton;
    @FXML
    private VBox content;
    private String studentId;
    JSONObject response = new JSONObject();
    public void initialize() throws IOException {
        Circle clip = new Circle(avatar.getFitWidth() / 2, avatar.getFitHeight() / 2, Math.min(avatar.getFitWidth() , avatar.getFitHeight()) / 2);
        avatar.setClip(clip);
        if (Globalvar.userRole.equals("STUDENT")) {
            setStudentInfo(String.valueOf(Globalvar.specificId));
        }
        if (Globalvar.userRole.equals("TEACHER")) {
            setTeacherInfo(String.valueOf(Globalvar.specificId));
        }
        basicInformation.setOnAction(e -> {
            try {
                changeContentByScene("base/student-info-detail", getDetailNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        academicButton.setOnAction(e->{
            try {
                changeContentByScene("base/academic-performance",getAcademicNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        honorsButton.setOnAction(e->{
            try {
                changeContentByScene("base/honor-page",getHonorNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    }

    public void setStudentInfo(String id) throws IOException {
        studentId = id;
        Map<String,String> genderMap = new HashMap<>();
        genderMap.put("male","男");
        genderMap.put("female","女");

        response = HttpUtil.get(Globalvar.baseUrl+"/api/students/"+id)
                .header("Accept", "application/json") // 设置请求头（如果需要的话）
                .asJson().getBody().getObject();
        System.out.println(response);
        studentInfo.put("name",(String)response.get("name"));
        studentInfo.put("gender",genderMap.get((String)response.get("gender")));
        studentInfo.put("birthday",(String)response.get("birthday"));
        studentInfo.put("province",(String)response.get("province"));
        studentInfo.put("email",(String)response.get("email"));
        studentInfo.put("telephone",String.valueOf(response.get("telephone")));
        studentInfo.put("homeAddress",(String)response.get("homeAddress"));
        studentInfo.put("personalInfo",(String)response.get("personalInfo"));

        System.out.println("准备发请求");
        this.name.setText((String)response.get("name"));
        this.id.setText(id);
        this.category.setText((String)response.get("belonging"));
        HttpResponse avatarRes = HttpUtil.get(Globalvar.baseUrl+"/api/users/"+id+"/avatar")
                .header("Accept", "application/json") // 设置请求头（如果需要的话）
                .asBytes();
        System.out.println("收到响应");
        Image img;
        System.out.println(avatarRes.getStatus());
        if(avatarRes.getStatus() != 200){
            img = new Image(getClass().getResource("/com/teach/javafxclient/picture/用户-圆.png").toExternalForm());
        }else{
            img = new Image(new ByteArrayInputStream((byte[]) avatarRes.getBody()));
        }
        double wid = Math.min(img.getWidth() , img.getHeight());
        Circle clip = new Circle(avatar.getFitWidth() / 2, avatar.getFitHeight() / 2, Math.min(avatar.getFitWidth() , avatar.getFitHeight()) / 2);
        avatar.setClip(clip);
        Rectangle2D viewport = new Rectangle2D(img.getWidth()/2 - wid/2, img.getHeight()/2 - wid/2, wid, wid);
        avatar.setViewport(viewport);
        avatar.setImage(img);
    }
    public void setTeacherInfo(String teacherId ) throws IOException {
        response = HttpUtil.get(Globalvar.baseUrl+"/api/teachers/"+teacherId)
                .header("Accept", "application/json") // 设置请求头（如果需要的话）
                .asJson().getBody().getObject();
        basicInformation.setManaged(false);
        basicInformation.setVisible(false);
        academicButton.setVisible(false);
        academicButton.setManaged(false);
        honorsButton.setVisible(false);
        honorsButton.setManaged(false);
        activityButton.setVisible(false);
        activityButton.setManaged(false);


        this.name.setText((String)response.get("name"));
        this.id.setText(teacherId);
        this.category.setText((String)response.get("collegeName"));
        HttpResponse avatarRes = HttpUtil.get(Globalvar.baseUrl+"/api/users/"+teacherId+"/avatar")
                .header("Accept", "application/json") // 设置请求头（如果需要的话）
                .asBytes();
        System.out.println("收到响应");
        Image img;
        System.out.println(avatarRes.getStatus());
        if(avatarRes.getStatus() != 200){
            img = new Image(getClass().getResource("/com/teach/javafxclient/picture/用户-圆.png").toExternalForm());
        }else{
            img = new Image(new ByteArrayInputStream((byte[]) avatarRes.getBody()));
        }
        double wid = Math.min(img.getWidth() , img.getHeight());
        Circle clip = new Circle(avatar.getFitWidth() / 2, avatar.getFitHeight() / 2, Math.min(avatar.getFitWidth() , avatar.getFitHeight()) / 2);
        avatar.setClip(clip);
        Rectangle2D viewport = new Rectangle2D(img.getWidth()/2 - wid/2, img.getHeight()/2 - wid/2, wid, wid);
        avatar.setViewport(viewport);
        avatar.setImage(img);

        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/course-list.fxml"));
        Parent root = fxmlLoader.load();
        CourseListController CLC = fxmlLoader.getController();
        CLC.set(teacherId);
        content.getChildren().add(root);
    }
    protected  void changeContent(String name, String title,Button button) {
        if(temp != null){
            temp.setStyle("-fx-text-fill: black");
        }
        button.setStyle("-fx-text-fill: #670202");
        temp = button;
        Node node;
        Object c;
        node = paneMap.get(name);
        if( node == null) {
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource(name + ".fxml"));
            try {
                node = fxmlLoader.load();
                paneMap.put(name, node);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            c = fxmlLoader.getController();
        }
        content.getChildren().clear();
        content.getChildren().add(node);
    }
    Node getDetailNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/student-info-detail.fxml"));
        Parent root = fxmlLoader.load();
        StudentInfoDetailController SIDC = fxmlLoader.getController();
        SIDC.address.setText(studentInfo.get("homeAddress"));
        SIDC.name.setText(studentInfo.get("name"));
        SIDC.gender.setText(studentInfo.get("gender"));
        SIDC.birthday.setText(studentInfo.get("birthday"));
        SIDC.source.setText(studentInfo.get("province"));
        SIDC.email.setText(studentInfo.get("email"));
        SIDC.phoneNumber.setText(studentInfo.get("telephone"));
        SIDC.personalSolution.setText(studentInfo.get("personalInfo"));
        SIDC.setInfo.setOnMouseClicked(e->{
            try {
                Node edit = getEditStudentNode();
                paneMap.put("base/student-info-detail",edit);
                content.getChildren().clear();
                content.getChildren().add(edit);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        return root;
    }
    Node getEditStudentNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/edit-student-info.fxml"));
        Parent root = fxmlLoader.load();
        EditStudentInfoController ESIC = fxmlLoader.getController();
        ESIC.setInfo(studentInfo.get("province"),studentInfo.get("gender"),studentInfo.get("telephone"),studentInfo.get("email"),studentInfo.get("homeAddress"),studentInfo.get("personalInfo"),studentId,response);
        ESIC.back.setOnAction(e->{
            paneMap.remove("base/student-info-detail");
            try {
                changeContentByScene("base/student-info-detail", getDetailNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        return root;
    }
    Node getAcademicNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/academic-performance.fxml"));
        Parent root = fxmlLoader.load();
        AcademicPerformanceController APC = fxmlLoader.getController();
        APC.set(studentId);
        return root;
    }
    Node getHonorNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/honor-page.fxml"));
        Parent root = fxmlLoader.load();
        HonorPageController HIC = fxmlLoader.getController();
        HIC.set(Long.valueOf(studentId));
        return root;
    }
    protected  void changeContentByScene(String name, Node n,Button button) {
        if(temp != null){
            temp.setStyle("-fx-text-fill: #707070;-fx-background-color: white");
            temp.setUnderline(false);
        }
        button.setStyle("-fx-text-fill: #670202;-fx-background-color: white");
        button.setUnderline(true);
        temp = button;
        Node node;
        Object c;
        node = paneMap.get(name);
        if( node == null) {
            node = n;
        }
        content.getChildren().clear();
        content.getChildren().add(node);
    }
}
